//
//  OutstandingMapController.swift
//  ExpressDriver
//
//  Created by sheng on 2017/11/16.
//  Copyright © 2017年 sheng. All rights reserved.
//

import UIKit
import MapKit

class OutstandingMapController: UIViewController, MKMapViewDelegate, UIScrollViewDelegate {
    
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var mapView: MKMapView!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    var courses = [
        ["name":"order info 1","pic":"chart.png"],
        ["name":"order info 2","pic":"page.png"],
        ["name":"order info 3","pic":"history.png"]
    ]
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI();
        // 1.
        self.mapView.delegate = self
        
        mapView.userTrackingMode = .follow
        //地图的显示风格，此处设置使用标准地图
        mapView.mapType = .standard
        //地图是否可滚动，默认为true
        mapView.isScrollEnabled = true
        //地图是否缩放，默认为true
        mapView.isZoomEnabled = true
        //是否显示用户当前位置 ios8之后才有，默认为false
        mapView.showsUserLocation = true
        
        // 2.苹果在中国区域默认使用高德地图，这里使用北京的两个地点
        let sourceLocation = CLLocationCoordinate2D(latitude: 39.906421, longitude: 116.397633)
        let destinationLocation = CLLocationCoordinate2D(latitude: 39.935865, longitude: 116.455381)
        
        // 3.
        let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
        let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
        
        // 4.
        let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
        
        // 5.
        let sourceAnnotation = MKPointAnnotation()
        //sourceAnnotation.title = "Tian'anmen Square"
        
        if let location = sourcePlacemark.location {
            sourceAnnotation.coordinate = location.coordinate
        }
        
        
        let destinationAnnotation = MKPointAnnotation()
        //destinationAnnotation.title = "Taikoo Li Sanlitun"
        
        if let location = destinationPlacemark.location {
            destinationAnnotation.coordinate = location.coordinate
        }
        
        // 6.
        self.mapView.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )
        
        // 7.
        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceMapItem
        directionRequest.destination = destinationMapItem
        directionRequest.transportType = .automobile
        
        // Calculate the direction
        let directions = MKDirections(request: directionRequest)
        
        // 8.
        directions.calculate { (response, error) in
            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }
                return
            }
            
            let route = response.routes[0]
            self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)
            
            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }
        
    }
    
    
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.red
        renderer.lineWidth = 3.0
        return renderer
    }
    
    
    
    func setUI()  {
        scrollView.contentSize = CGSize(
            width: CGFloat(self.view.bounds.width - 30) * CGFloat(self.courses.count),
            height: CGFloat(235)
        )
        //关闭滚动条显示
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.scrollsToTop = false
        //协议代理，在本类中处理滚动事件
        scrollView.delegate = self
        //滚动时只能停留到某一页
        scrollView.isPagingEnabled = true
        //添加页面到滚动面板里
        
        
        scrollView.backgroundColor = UIColor.white
        scrollView.layer.borderColor = UIColor.lightGray.cgColor
        scrollView.layer.borderWidth = 0.5
        scrollView.layer.cornerRadius = 8
        scrollView.bounces = false
        
        self.scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(0)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(200)
        }
        
        
        let size = scrollView.bounds.size
        let scroWidth = scrollView.bounds.size.width - 30
        print("宽度\(scroWidth)")
        
        for (seq,course) in courses.enumerated() {
            let page = UIView()
            
            let lbl = UILabel(frame: CGRect(x: 10, y: 20, width: 100, height: 20))
            lbl.text = course["name"]
            page.addSubview(lbl)
            
            page.frame = CGRect(x: CGFloat(seq) * scroWidth, y: 0,
                                width: scroWidth, height: size.height)
            
            scrollView.addSubview(page)
        }
        
        
        
        self.pageControl.snp.makeConstraints { (make) in
            make.top.equalTo(scrollView.snp.bottom).offset(5)
            make.height.equalTo(10)
            make.centerX.equalTo(self.view)
        }
        
        
        self.mapView.snp.makeConstraints { (make) in
            make.left.equalTo(0)
            make.top.equalTo(pageControl.snp.bottom).offset(5)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
        }
        
        pageControl.currentPageIndicatorTintColor = UIColor.black
        pageControl.pageIndicatorTintColor = UIColor.gray
        
        pageControl.numberOfPages = courses.count
        pageControl.currentPage = 0
        //设置页控件点击事件
        pageControl.addTarget(self, action: #selector(pageChanged(_:)),
                              for: UIControlEvents.valueChanged)
    }
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //UIScrollViewDelegate方法，每次滚动结束后调用
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //通过scrollView内容的偏移计算当前显示的是第几页
        let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
        //设置pageController的当前页
        pageControl.currentPage = page
        print("当前第\(page)页")
    }
    
    //点击页控件时事件处理
    func pageChanged(_ sender:UIPageControl) {
        //根据点击的页数，计算scrollView需要显示的偏移量
        var frame = scrollView.frame
        frame.origin.x = frame.size.width * CGFloat(sender.currentPage)
        frame.origin.y = 0
        //展现当前页面内容
        scrollView.scrollRectToVisible(frame, animated:true)
    }

}
